package com.hnevc.restaurant.controller;
import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hnevc.restaurant.entity.UploadFile;

@Controller
@RequestMapping("/File")
public class FileController {
	@RequestMapping(value="/upload", method=RequestMethod.GET)
	public String showUploadPage(){
		return "file";
	}
	@RequestMapping(value="/doUpload",method=RequestMethod.POST)
	@ResponseBody
	public UploadFile doUploadFile(@RequestParam("file")MultipartFile multipartFile, 
			HttpServletRequest request) throws IOException{
		UploadFile uploadFile=null; 
		if(!multipartFile.isEmpty()){
			String realFileName = System.currentTimeMillis()+multipartFile.getOriginalFilename();
			File file = new File(request.getSession().getServletContext().getRealPath("/uploadFoodImage/"),
					realFileName);
			FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
			uploadFile= new UploadFile();
			uploadFile.setFilePath(file.getAbsolutePath());
			uploadFile.setOriginalFileName(multipartFile.getOriginalFilename());
			uploadFile.setRealFileName(realFileName);
		}
		return uploadFile;
	}
	@RequestMapping(value="/doUploadfiles",method=RequestMethod.POST)
	public String doUploadFiles(@RequestParam("file")MultipartFile[] multipartFiles
			,HttpServletRequest request) throws IOException{	
		if(!multipartFiles[0].isEmpty()){
			
			File file = new File(request.getSession().getServletContext().getRealPath("/uploadFoodImage/")
					,System.currentTimeMillis()+multipartFiles[0].getOriginalFilename());
			
			FileUtils.copyInputStreamToFile(multipartFiles[0].getInputStream(), file);
		}
		
		return "success";
	}
}